package main

import (
	"context"
	"log"
	"os"
	"os/signal"
	_ "simple-http-server/internal/store"
	"simple-http-server/server"
	"simple-http-server/store/factory"
	"syscall"
	"time"
)

func main() {
	repository, err := factory.NewBookRepository("mem")
	if err != nil {
		panic(err)
	}
	bookServer := server.NewBookServer(":8080", repository)
	errChan, err := bookServer.ListenAndServer()
	if err != nil {
		log.Println("web server start faild:", err)
		return
	}
	signals := make(chan os.Signal, 1)
	signal.Notify(signals, syscall.SIGINT, syscall.SIGTERM)

	select {
	case err = <-errChan:
		log.Println("web server run faild:", err)
		return
	case <-signals:
		log.Println("bookstore program is exiting...")
		ctx, cancelFunc := context.WithTimeout(context.Background(), time.Second)
		defer cancelFunc()
		err = bookServer.Shutdown(ctx)
	}
	if err != nil {
		log.Println("bookstore program exit error:", err)
		return
	}
	log.Println("bookstore program exit ok")

}
